package com.changan.controller;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.changan.entity.Menu;
import com.changan.response.Result;
import com.changan.service.MenuService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 菜单表 前端控制器
 * </p>
 *
 * @author NieChangan
 * @since 2022-08-29
 */
@Api(tags = "菜单权限接口")
@RestController
@RequestMapping("/menu")
@CrossOrigin
public class MenuController {

    @Autowired
    private MenuService menuService;

    @Autowired
    private RedisTemplate redisTemplate;

    @ApiOperation(value = "加载菜单树", notes = "获取所有菜单树，以及展开项")
    @GetMapping("/tree")
    public Result tree() {

        //1.查询所有的菜单
        List<Menu> menuTree = menuService.findMenuTree();

        //2.查询哪些菜单是展开的
        List<Long> ids = menuService.findOpenIds();

        Map<String,Object> map = new HashMap<>();
        map.put("menuTree",menuTree);
        map.put("ids",ids);
        return Result.ok().data(map);
    }

    /**
     * 设置验证码
     * @return
     */
    @PostMapping("/setCode")
    public Result setCode(){
        String code = RandomUtil.randomNumbers(6);
        redisTemplate.opsForValue().set("code",code,10, TimeUnit.SECONDS);
        return Result.ok().data("code",code);
    }

    @GetMapping("/getCode")
    public Result getCode(){
        Object code = redisTemplate.opsForValue().get("code");
        if(code==null){
            return Result.error().message("验证码已经过期");
        }
        return Result.ok().data("code",code);
    }
}
